/**
 * File: LoadContigIdxController.java
 * Created by: mhaimel
 * Created on: 2 Oct 2009
 * CVS:  $Id: LoadContigIdxController.java,v 1.1 2009/10/09 14:55:50 mhaimel Exp $
 */
package uk.ac.ebi.curtain.controller.loader;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import uk.ac.ebi.curtain.controller.SingleSubmitController;
import uk.ac.ebi.curtain.utils.CurtainUncheckedException;
import uk.ac.ebi.curtain.utils.data.ReadType;
import uk.ac.ebi.curtain.utils.io.impl.FileIO;

/**
 * @author mhaimel
 *
 */
public class LoadContigIdxController extends SingleSubmitController<Serializable, Serializable> {

	@Override
	protected void singleSubmit(List<Serializable> inputList) {
		File ctgFile = getContext().currentFiles().getIndexFile(ReadType.Contig);
		{
			Integer ctgCnt = loadContigIds(ctgFile);
			getLog().debug("Loaded Contig ids: " + ctgCnt);
			if(!ctgCnt.equals(getContext().getContigIndex().getSize())){
				throw new IllegalArgumentException("Contig sizes don't match up: " + getContext().getContigIndex().getSize() + " <> " + ctgCnt);
			}
		}
		getLog().debug("Finished Loading Contig ids!");
		for(Serializable s : inputList){
			// pass on the results
			submit(s);
		}
	}

	private Integer loadContigIds(File ctgFile) {
		Integer cnt = 0;
		BufferedReader in = null;
		try {
			in = new FileIO(ctgFile).getBufferedReader();
			String line = StringUtils.EMPTY;
			while((line = in.readLine()) != null){
				if(StringUtils.isNotBlank(line)){
					String[] arr = line.split("\t");
					Integer id = Integer.valueOf(arr[0]);
					String idstr = arr[1];
					getContext().getContigIndex().registerIdentifier(idstr, id);
					++cnt;
				}
			}
		} catch (IOException e) {
			throw new CurtainUncheckedException("Problems reading file " + ctgFile);
		}finally{
			FileIO.closeQuietly(in);
		}
		return cnt;
	}	
}
